package yunhe.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;

import yunhe.biz.ProBiz;
import yunhe.entity.Product;


@WebServlet(name="ProServlet",urlPatterns="/ProductServlet")
public class ProductServlet extends HttpServlet{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		ProBiz proBiz=new ProBiz();
		String pageIndex=req.getParameter("pageIndex");
		if(pageIndex==null){
			pageIndex="1";
		}
		int curPage=Integer.parseInt(pageIndex);
		int proCount=proBiz.getProCount();
		int pageSize=10;
		int totalPages=proCount%pageSize==0?proCount/pageSize:proCount/pageSize+1;
		req.setAttribute("totalPages", totalPages);		
		if(curPage<1){
			curPage=1;
		}else if(curPage>totalPages){
			curPage=totalPages;
		}
		String search=req.getParameter("search");
		String searchText=req.getParameter("searchText");
		HashMap<String,String> searchMap=new HashMap<>();
		searchMap.put("search", search);
		searchMap.put("searchText", searchText);
		ArrayList<Product> proList=proBiz.getAllProduct(searchMap);
		System.out.println(proList);
		JSONArray jsonArray=new JSONArray();
		if(!proList.isEmpty()){
	         for (int i=0;i<proList.size();i++){
	             Map<String,String> mss=new HashMap<String,String>();
	             mss.put("proBarCode",proList.get(i).getProBarCode());
	             mss.put("proNumber",proList.get(i).getProNumber());
	             mss.put("proName",proList.get(i).getProName());
	             mss.put("proQual",proList.get(i).getProQual());
	             mss.put("proUnit",proList.get(i).getProUnit());
	             mss.put("proAddr",proList.get(i).getProAddr());
	             mss.put("proClass",proList.get(i).getProClass());
	             mss.put("proPurchPrice",proList.get(i).getProPurchPrice()+"");
	             mss.put("proSalePrice",proList.get(i).getProSalePrice()+"");
	             jsonArray.put(mss);
	         }
	     }
		String str="{\"total\":"+proCount+",\"rows\":"+jsonArray.toString()+"}";
		resp.getWriter().print(str);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		System.out.println("����Post����");
		doGet(req, resp);
	}
}
